'use strict';

const { Service } = require('ee-core');
const amqp = require('amqplib');
const Log = require('ee-core/log');
const Base64 = require('base-64'); // 引入base-64库
const { error } = require('ee-core/log');
const Services = require('ee-core/services');
const Conf = require('ee-core/config');

const serverConfig = Conf.getValue('main').amqplib;


/**
 * amqp
 * @class
 */
class AmqpService extends Service {

  constructor(ctx) {
    super(ctx);
  }

  initQueue(queueName) {
    function receivedMessageCallBack(content) {
		let msg = Base64.decode(content);
		Log.info('接收MQ消息:' + msg);
    let msgObj = JSON.parse(msg)
		let { CMD } = msgObj
		switch(CMD) {
			case 'CMD_UP_STATUS': // 上传状态
			Services.get('api').uploadDeviceStatus(queueName).then(res => {
				// Log.info("")
			});
			break;
			case 'CMD_PUB_PROGRAM': // 节目发布
				// 获取节目详细信息
				Services.get('api').getProgramInfo(queueName, msgObj.ID).then(res => {
					Log.info("返回节目信息:"+JSON.stringify(res))
					if (res.code == 0) {
						let programJson = res.data.programjson;
						Services.get('program.program').downloadByOrder(programJson, msgObj.ID);
						//Services.get('program.program').parseProgram(programJson, msgObj.ID);
					} else {
						Log.error("返回节目信息错误："+JSON.stringify(res));
					}
				}).catch(error => {
					Log.error("获取节目信息异常:"+error);
				})
			break;
      case 'CMD_UPLOAD_MONITOR':  // 上传监控信息
        Services.get('api').screenShot();
      break;
      case 'SHUTDOWN': // 关机
        Services.get('system').shutdown();
      break;
      case 'REBOOT': // 重启
        Services.get('system').reboot();
      break;
      case 'CMD_ADJUST_VOLUME': // 调整系统音量
        
        Services.get('system').setSound(msgObj.VALUE);
      break;
		}
        // let notification = new Notification({
        //   title: msgTitle, // 通知的标题, 将在通知窗口的顶部显示
        //   body: msgContent, // 通知的正文文本, 将显示在标题或副标题下面
        //   silent: true // 在显示通知时是否发出系统提示音
        // })
        // notification.show()
  
        // // 被点击之后通知渲染进程
        // notification.on('click', e => {
        //   notification.close()
        //   console.log(e.sender.title)
        //   webContents.send('ON_NOTIFICATION_CLICK', {
        //     title: e.sender.title,
        //     body: e.sender.body
        //   })
        // })
      }
  
      amqp.connect(serverConfig).then(
        conn => {
          console.log('创建连接成功')
          conn.createChannel().then(
            ch => {
              console.log('创建Channel成功')
              ch.assertQueue(queueName, {
                durable: true // 队列不进行持久化
              })
              // // 注册一个 渲染进程调用的方法
              // ipcMain.handle('SEND_MQ_MESSAGE', async (event, msgObj) => {
              //   console.log('sendMsg', msgObj)
              //   ch.sendToQueue(queueName, Buffer.from(JSON.stringify(msgObj)))
              // })
  
              ch.consume(
                queueName,
                function(msg) {
                  receivedMessageCallBack(msg.content.toString())
                },
                {
                  noAck: true
                }
              ).catch(e => {
                Log.error("amqp consume exception:"+e);
              })
            },
            err => {
              console.log('创建Channel 错误:' + err)
            }
          )
        },
        err => {
          console.log('连接MQ Server 错误:' + err)
        }
      ).catch(e => {
        Log.error("amqp connect exception:"+e);
      })
    }
  

}

AmqpService.toString = () => '[class AmqpService]';
module.exports = AmqpService;  